import 'dart:async';
import 'dart:io';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/choose_city/bean/choose_city_list_item_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_create_or_edit_address_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_logo_detail_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/custom_length_limiting_text_input_formatter.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'dart:math' as math;

/// 品牌或门店名称
class CreateSmartHomePage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "CreateSmartHomePage";

  static const String DETAIL_ADDRESS_KEY = "detail_address";

  static const String GPS_KEY = "gps";

  const CreateSmartHomePage(
      {Key key,}) : super(key:key);

  @override
  _CreateSmartHomePageState createState() => _CreateSmartHomePageState();

  static Future<Map> navigatorPush(BuildContext context,){
    return RouterUtils.routeForFutureResult(
        context,
        CreateSmartHomePage(),
        routeName: CreateSmartHomePage.ROUTER
    );
  }
}

class _CreateSmartHomePageState
    extends BaseState<CreateSmartHomePage> {

  TextEditingController _brandNameController;
  TextEditingController _storeNameController;
  //指示牌标题
  SmartHomeViewModel _viewModel;
  String _brandName = "";
  String _storeName = "";
  String _logo = "";
  String _address = "";


  String _province;
  String _city ;
  String _district;
  String _gps;
  String _addressCode;
  String _detailAddress;


  @override
  void initState() {
    super.initState();
    _viewModel = SmartHomeViewModel(this);
    _brandNameController = TextEditingController(text: _brandName);
    _storeNameController = TextEditingController(text: _storeName);
  }




  @override
  void dispose() {
    _brandNameController.clear();
    _brandNameController.dispose();
    _storeNameController.clear();
    _storeNameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: _toMainColumnWidget(),
        )
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        _toSmartHomeBrandNameWidget(),
        SizedBox(height: 1,),
        _toSmartHomeStoreNameWidget(),
        // SizedBox(height: 10,),
        // _toLogoWidget(),
        SizedBox(height: 1,),
        _toAddressWidget(),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "创建门店",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toSaveButtonWidget(),
    );
  }

  Widget _toSaveButtonWidget() {
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: isCanSave(),
      width: 48,
      height: 24,
      unSelectBgColor:Color(0xFFCFD4DB),
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
          color: Colors.white,
          fontSize: 12,
          fontWeight: FontWeight.w600),
      selectedTextStyle: TextStyle(
          color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
      text: "保存",
      onTap: (){
        _save();
      },
    );
  }

  void _save(){
    if(!isCanSave()){
      return;
    }
    if(StringUtils.isNotEmpty(_logo) && !PhotoPreviewToolUtils.isNetUrl(_logo)){
      VgHudUtils.show(context, "创建中");
      VgMatisseUploadUtils.uploadSingleImage(
          _logo,
          VgBaseCallback(onSuccess: (String netPic) {
            if (StringUtils.isNotEmpty(netPic)) {
              //编辑
              _viewModel.createStore(context, _brandName.trim(), _storeName.trim(), netPic,
                      _province, _city, _district, _detailAddress, _gps, _addressCode,
                      (String id){
                Map map={'brand': _brandName.trim(), 'title': _storeName.trim(), 'id': id};
                RouterUtils.pop(context, result: map);
              });
            } else {
              VgToastUtils.toast(context, "Logo上传失败");
            }
          }, onError: (String msg) {
            VgToastUtils.toast(context, msg);
          }));
    }else{
      _viewModel.createStore(context, _brandName.trim(), _storeName.trim(), null,
          _province, _city, _district, _detailAddress, _gps, _addressCode,
              (String id){
                Map map={'brand': _brandName.trim(), 'title': _storeName.trim(), 'id': id};
        RouterUtils.pop(context, result: map);
      });
    }
  }

  ///品牌名称
  Widget _toSmartHomeBrandNameWidget(){
    return Container(
      height: 50,
      color: Colors.white,
      padding: EdgeInsets.only(right: 15),
      child: Row(
        children: [
          Container(
            width: 15,
            alignment: Alignment.centerRight,
            padding: EdgeInsets.only(right: 2),
            child: Text(
              "*",
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFFFF404D),
              ),
            ),
          ),
          Text(
            "品牌名称",
            style: TextStyle(
              fontSize: 14,
              color: Color(0XFF21263C),
            ),
          ),
          SizedBox(width: 15,),
          Expanded(
            child: Container(
              alignment: Alignment.centerLeft,
              child: VgTextField(
                controller: _brandNameController,
                keyboardType: TextInputType.text,
                autofocus: true,
                textAlign: TextAlign.left,
                style: TextStyle(
                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    fontSize: 14),
                decoration: new InputDecoration(
                    counterText: "",
                    hintText: "请输入",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize: 14,
                        color: Color(0XFFB0B3BF))),
                maxLimitLength: Platform.isAndroid?8:null,
                zhCountEqEnCount: true,
                limitCallback:(int){
                  Platform.isAndroid?VgToastUtils.toast(context, "最多可输入8个字"):{};
                },
                maxLines: 1,
                onChanged: (value){
                  // int position = CustomLengthLimitingTextInputFormatter.getMaxLimtCharPositionForStr(value,
                  //     maxLimitCount: 8, zhCountEqEnCount: true);
                  // if(position != null && position > 0){
                  //   _brandNameController?.text = value.substring(0, 8);
                  //   _brandNameController.selection = TextSelection.fromPosition(TextPosition(
                  //       affinity: TextAffinity.downstream,
                  //       offset: 8));
                  //   VgToastUtils.toast(context, "最多可输入8个字");
                  // }
                  _notifyChange();
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///门店名称
  Widget _toSmartHomeStoreNameWidget(){
    return Container(
      height: 50,
      color: Colors.white,
      padding: EdgeInsets.only(right: 15),
      child: Row(
        children: [
          Container(
            width: 15,
            alignment: Alignment.centerRight,
            padding: EdgeInsets.only(right: 2),
            child: Text(
              "*",
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFFFF404D),
              ),
            ),
          ),
          Text(
            "门店名称",
            style: TextStyle(
              fontSize: 14,
              color: Color(0XFF21263C),
            ),
          ),
          SizedBox(width: 15,),
          Expanded(
            child: Container(
              alignment: Alignment.centerLeft,
              child: VgTextField(
                controller: _storeNameController,
                keyboardType: TextInputType.text,
                autofocus: true,
                textAlign: TextAlign.left,
                style: TextStyle(
                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    fontSize: 14),
                decoration: new InputDecoration(
                    counterText: "",
                    hintText: "如：居然之家十里河店",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize: 14,
                        color: Color(0XFFB0B3BF))),
                maxLimitLength: Platform.isAndroid?10:null,
                zhCountEqEnCount: true,
                limitCallback:(int){
                  Platform.isAndroid?VgToastUtils.toast(context, "最多可输入10个字"):{};
                },
                maxLines: 1,
                onChanged: (value){
                  // int position = CustomLengthLimitingTextInputFormatter.getMaxLimtCharPositionForStr(value,
                  //     maxLimitCount: 10, zhCountEqEnCount: true);
                  // int end = _storeNameController.value.selection.end;
                  // int start = _storeNameController.value.selection.start;
                  // print("onChanged：" + position.toString() + ", " + start.toString() + ", " + end.toString());
                  // if(position != null && position > 0){
                  //   _storeNameController?.text = value.substring(0, 10);
                  //   _storeNameController.selection = TextSelection.fromPosition(TextPosition(
                  //       affinity: TextAffinity.downstream,
                  //       offset: 10));
                  //   VgToastUtils.toast(context, "最多可输入10个字");
                  // }
                  _notifyChange();
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///门店logo
  Widget _toLogoWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        VgToolUtils.removeAllFocus(context);
        if(StringUtils.isEmpty(_logo)){
          String path = await MatisseUtil.clipOneImage(context, scaleX: 1, scaleY: 1, isCanSelectRadio: false);
          if (path == null || path == "") {
            return;
          }
          _logo = path;
          setState(() {});
          return;
        }
        SmartHomeLogoDetailPage.navigatorPush(context, _logo,  (path, cancelLoadingCallback) {
          RouterUtils.pop(context);
          _logo = path;
          setState(() {});
        },(){
          RouterUtils.pop(context);
          setState(() {
            _logo = "";
          });
        },);
      },
      child: Container(
        height: 50,
        alignment: Alignment.center,
        color: Colors.white,
        child: Row(
          children: [
            SizedBox(width: 15,),
            Text(
              "品牌Logo",
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFF21263C),
              ),
            ),
            SizedBox(width: 10,),
            StringUtils.isNotEmpty(_logo)?ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: Container(
                width: 30,
                height: 30,
                alignment: Alignment.center,
                child: VgCacheNetWorkImage(
                  _logo,
                ),
              ),
            ):
            Text(
              "选填",
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFFB0B3BF),
              ),
            ),
            Spacer(),
            SizedBox(width: 9,),
            Image.asset(
              "images/icon_arrow_right_grey.png",
              width: 6,
              color: Color(0XFF8B93A5),
            ),
            SizedBox(width: 15,),
          ],
        ),
      ),
    );
  }

  ///门店地址
  Widget _toAddressWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        Map<String, ChooseCityListItemBean> result =
            await SmartHomeCreateOrEditAddressPage.navigatorPush(context, "",
                _gps??"", _province??"", _city??"", _district??"", _detailAddress??"", _addressCode??"", (address, gps){
              _detailAddress = address;
              _gps = gps;
            });
        if(result == null){
          return;
        }
        _addressCode = result[CHOOSE_DISTRICT_KEY]?.sid;
        _province = result[CHOOSE_PROVINCE_KEY]?.sname;
        _city = result[CHOOSE_CITY_KEY]?.sname;
        _district = result[CHOOSE_DISTRICT_KEY]?.sname;
        _address = _getAddressStr(_detailAddress);
        setState(() { });
      },
      child: Container(
        height: 50,
        alignment: Alignment.center,
        color: Colors.white,
        child: Row(
          children: [
            SizedBox(width: 15,),
            Text(
              "门店地址",
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFF21263C),
              ),
            ),
            SizedBox(width: 15,),
            Text(
              StringUtils.isNotEmpty(_detailAddress)?_detailAddress:"选填",
              style: TextStyle(
                fontSize: 14,
                color: StringUtils.isNotEmpty(_detailAddress)?Color(0XFF21263C):Color(0XFFB0B3BF),
              ),
            ),
            Spacer(),
            SizedBox(width: 9,),
            Image.asset(
              "images/icon_arrow_right_grey.png",
              width: 6,
              color: Color(0XFF8B93A5),
            ),
            SizedBox(width: 15,),
          ],
        ),
      ),
    );
  }

  String _getAddressStr(String detailAddress) {
      if (_province == _city) {
        return "$_province$_district$detailAddress";
      } else {
        return "$_province$_city$_district$detailAddress";
      }

  }

  ///通知更新
  _notifyChange() {
    _brandName = _brandNameController?.text?.trim();
    if(_brandName.length > 8){
      _brandName = _brandName.substring(0, 8);
    }
    _storeName = _storeNameController?.text?.trim();
    if(_storeName.length > 10){
      _storeName = _storeName.substring(0, 10);
    }
    setState(() { });
  }

  bool isCanSave(){
    return StringUtils.isNotEmpty(_brandName) && StringUtils.isNotEmpty(_storeName);
  }
}
